package com.lhh.springcommon.interceptor;

import com.lhh.springcommon.exception.CustomException;
import com.lhh.springcommon.utils.CodeEnum;
import com.lhh.springcommon.config.RequestConfigurationProperties;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * 幂等拦截器
 * @author 李厚航
 */
@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RequestConfigurationProperties requestConfigurationProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //获取所有请求头
        StringBuilder headersString = new StringBuilder("[");
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headersString.append(headerName).append(":").append(request.getHeader(headerName)).append(",");
        }
        //删除最后一个逗号
        headersString.deleteCharAt(headersString.length()-1);
        headersString.append("]");
        log.info("[Request URL: {},HTTP Method: {}，IP: {}，TIME: {}，Parameters: {}，HEADERS: {}]",
                request.getRequestURL(),
                request.getMethod(),
                request.getRemoteAddr(),
                LocalDateTime.now(),
                request.getQueryString(),
                headersString);
        String requestId = request.getHeader("requestId");
        if(requestId==null){
            throw new CustomException(CodeEnum.HEADER_NOT_REQUEST_ID);
        }
        RBucket<String> bucket = redissonClient.getBucket(requestConfigurationProperties.getIdPrefix() + ":" + requestId);
        if(bucket.get()!=null){
            //该请求已传入
            return false;
        }
        //新请求，存入redis后放行
        bucket.set("已保存，30秒后失效",requestConfigurationProperties.getTimeout(), TimeUnit.SECONDS);
        return true;
    }
}
